'use strict'

const { ApiController } = require('jax')

class AgentController extends ApiController {
  get Model() {
    return this.ctx.model.Agent
  }

  // 列表查询前
  beforeIndex() {
    const { ctx } = this
    const { query, helper } = ctx
    const filter = {}

    // 匹配搜索
    ;['isOpen'].map((key) => {
      if (query[key] && !query[key] == '') filter[key] = query[key]
    })

    // 关键字模糊查询
    if (query.keyword && !query.keyword == '') filter.agentName = new RegExp(helper.toMongoRegex(query.keyword, 'i'))

    return {
      filter,
    }
  }

  // 创建前
  async beforeCreate() {
    const { ctx } = this
    const { body } = ctx.request
  }

  // 保存前
  async beforeSave() {
    const { ctx } = this
    const { body } = ctx.request

    // 账户校验
    if (body.username) await ctx.service.systemUser.usernameVerify(body.username, body.adminId)
    // 手机号校验
    if (body.mobile) await ctx.service.systemUser.mobileVerify(body.mobile, body.adminId)
  }

  // 保存后
  async afterSave(agent) {
    const { ctx } = this
    const { body } = ctx.request

    await this.syncAdmin(body, agent)
  }

  // 注册或修改后台账号
  async syncAdmin(body, agent) {
    const { ctx } = this
    const { md5 } = ctx.helper
    const { ADMIN_PASSWORD, SYSTEM_TYPE_ADMIN } = this.config.constant

    const role = await ctx.model.AdminRole.findOne({
      roleName: '代理商',
    })

    const adminData = {
      systemType: SYSTEM_TYPE_ADMIN,
      roleId: role._id,
      sourceId: agent._id,
    }

    // 账号状态修改（状态/禁用）
    if (body.isOpen != undefined) adminData.isOpen = agent.isOpen

    // 用户修改
    if (body.username != undefined) adminData.username = body.username

    // 密码加密
    // if (body.password && body.password != '') body.password = md5(body.password)

    if (agent.adminId) {
      await ctx.model.Admin.updateOne(
        {
          _id: agent.adminId,
        },
        adminData
      )
    } else {
      const admin = await ctx.model.Admin.create({
        ...adminData,
        password: md5(ADMIN_PASSWORD),
      })
      agent.adminId = admin._id
      await agent.save()
    }
  }

  // 重置密码
  async resetPassword() {
    const { ctx, config } = this
    const { md5 } = ctx.helper
    const { admin } = ctx.state
    const { body } = ctx.request
    const { ADMIN_PASSWORD } = config.constant

    if (!admin.isAdmin) throw '没有操作权限'

    await ctx.model.Admin.updateOne({ _id: body.adminId }, { password: md5(ADMIN_PASSWORD) })
  }

  // 删除后
  async afterDestroy() {
    const { ctx } = this
    const { params } = ctx
    if (!this.isBatch) {
      const agentId = params.id
      await ctx.model.Admin.deleteOne({
        sourceId: agentId,
      })
    }
  }

  // 增加余额
  async addMoney() {
    const { ctx } = this
    const { body } = ctx.request
    const { helper } = ctx

    helper.validate(body, {
      required: ['agentId', 'money'],
    })

    // 增加用户积分
    await ctx.model.Agent.updateOne(
      { _id: body.agentId },
      {
        $inc: {
          money: body.money,
          totalMoney: body.money,
        },
      }
    )

    ctx.body = {
      code: 0,
      msg: '增加成功',
    }
  }
}

module.exports = AgentController
